package com.example.daily.data

import android.content.Context
import android.util.Log
import androidx.datastore.core.DataStore
import androidx.datastore.preferences.core.Preferences
import androidx.datastore.preferences.core.edit
import androidx.datastore.preferences.core.intPreferencesKey
import androidx.datastore.preferences.preferencesDataStore
import dagger.hilt.android.qualifiers.ApplicationContext
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.map
import javax.inject.Inject
import javax.inject.Singleton

private val Context.dataStore: DataStore<Preferences> by preferencesDataStore(name = "user_prefs")

@Singleton
class UserPreferences @Inject constructor(
    @ApplicationContext private val context: Context
) {
    private val userId = intPreferencesKey("user_id")

    fun getUserId(): Flow<Int?> = context.dataStore.data.map { preferences ->
        val id = preferences[userId]
        Log.d("UserPreferences", "Getting userId: $id")
        id
    }

    suspend fun saveUserId(id: Int) {
        Log.d("UserPreferences", "Saving userId: $id")
        context.dataStore.edit { preferences ->
            preferences[userId] = id
        }
    }

    suspend fun clearUserId() {
        Log.d("UserPreferences", "Clearing userId")
        context.dataStore.edit { preferences ->
            preferences.remove(userId)
        }
    }
} 